$(function() {


    //判断是否登录
    var userInfo = sessionStorage['users'];
    if (userInfo == null) {
        alert('请登录！');
        location.href = 'login.html';
        $('#userName').html("未登录");
        $('#login').html('登录/注册')
    } else {
        var user = JSON.parse(sessionStorage['users'])
        $('#userName').html(user[0].Name)
        $('#login').html('退出登录')
    }
    //获取local中的商品名
    var titles = localStorage['titles'];
    var goodName = JSON.parse(titles);
    var data = null;
    $.get('data/goods.json', function(response) {

        data = response;
        var strGoods = [];
        var num = {};
        for (let i = 0; i < goodName.length; i++) {
            var flag = true;
            var t = goodName[i].title;
            for (key in num) {
                if (key == t) {
                    num[key]++
                        flag = false
                }
            }
            if (flag) {
                num[t] = '1'
            }
            for (key in num) {
                if (goodName[i].title == key) {
                    goodsNum = num[key]

                }
            }
        }

        for (let j = 0; j < data.goods.length; j++) {
            for (key in num) {
                if (key == data.goods[j].title) {
                    strGoods += `
        <div class="good">
        <div>
            <input type="checkbox" name="product" id="" class="cb">
            
        </div>
        <div>
            <img class="goodsPic" src="${data.goods[j].imgPath}" alt="">
           
            <div class="goodsTitle" style="width: 200px; margin-top:auto; margin-bottom:auto;">
            ${data.goods[j].title}
            </div>
        </div>
        <div>
            ${data.goods[j].price}
        </div>
        <div>
            ${num[key]}
        </div>
        <div>
            ${data.goods[j].price * num[key]}
        </div>
        <div>
            <span class="col">
            <button>收藏</button>
            </span>
            <span class="del">
            <button>删除</button>
            </span>
        </div>
        </div>
        `;
                }
            }

        }
        $('.goods').html(strGoods);
        delDiv();
        collectionGoods();
        document.getElementsByClassName('btnSettlement')[0].onclick = function() {
            var buyTitles = [];
            console.log(goodName[1])
            for (let k = 0; k < goodName.length; k++) {
                buyTitles.push({
                    "goods": goodName[k]
                })
            }

            sessionStorage['buyGood'] = JSON.stringify(buyTitles)
            location.href = 'settlement.html'
        }
    })
    pickChecked();

    function delDiv() {
        var dels = document.getElementsByClassName('del');
        var del_length = dels.length;
        for (let i = 0; i < del_length; i++) {
            dels[i].onclick = function() {
                this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode)
                for (var x = 0; x < parseInt($(this).parent().parent().children().eq(3).text().replace(/\s*/g, "")); x++) {
                    var newStr = JSON.parse(localStorage.getItem('titles'));
                    for (var j = 0; j < newStr.length; j++) {
                        if (newStr[j].title.replace(/\s*/g, "") == $(this).parent().parent().children().eq(1).text().toString().replace(/\s*/g, "")) {
                            console.log($(this).parent().parent().children().eq(3).text().replace(/\s*/g, ""))
                            newStr.splice(j, 1);
                        }
                        localStorage['titles'] = JSON.stringify(newStr)
                    }
                }
            }
        }
    }

    function collectionGoods() {
        var collection = document.querySelectorAll('.col');
        var col_length = collection.length;
        for (let i = 0; i < col_length; i++) {
            collection[i].onclick = function() {
                var hasGoods = localStorage['collectProductionName']
                    // var hasGoods = JSON.parse(hasGoods)
                if (hasGoods == null) {
                    var colGoodName = []
                    colGoodName.push({
                        "title": $(this).parent().parent().children().eq(1).text().toString().replace(/(^\s*)|(\s*$)/g, "")
                    })
                } else {
                    var colGoodName = JSON.parse(localStorage['collectProductionName'])
                    colGoodName.push({
                        "title": $(this).parent().parent().children().eq(1).text().toString().replace(/(^\s*)|(\s*$)/g, "")
                    })
                }

                localStorage['collectProductionName'] = JSON.stringify(colGoodName)
            }
        }
    }
})

function pickChecked() {
    var all = document.getElementById('all');
    var products = document.getElementsByName('product');
    var count = 0;
    all.onclick = function() {
        for (let i = 0; i < products.length; i++) {
            products[i].checked = all.checked;
        }
        if (all.checked) {
            count = products.length
        } else {
            count = 0;
        }
        for (let i = 0; i < products.length; i++) {
            products[i].onclick = function() {
                this.checked == true ? count++ : count--;
                console.log(this.checked == true ? count++ : count--);
                if (count == 5) {
                    all.checked = true;
                } else {
                    all.checked = false;
                }

            }
        }
    }
}

var data = null;

function deleteItems() {
    var goods = $(".cb:checked");
    var len = goods.length;
    for (var i = 0; i < len; i++) {
        var tr = goods[i].parentNode.parentNode;
        var dell = tr.querySelector('.del').querySelector('button');
        dell.click();
    }
}

function out() {
    sessionStorage.clear()
    if ($('#login').html() == '退出登录') {
        location.href = 'index.html'
    } else {
        location.href = 'login.html'
    }
}